package sis.ra.founded;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import sis.ra.evaluation.seperateWikipediaArticleSentence;
import sis.ra.utility.Utils;


public class PatternwithVerb {

	public static Integer isVerb(String sentence, String pos, String verb)
	{
		Integer position=-1;
		//	System.out.println(pos);
		int verbpos=0;
		String [] lines=pos.split("\n");
		for (int i=0;i<lines.length;i++)
		{
			if (lines[i].contains(verb)&&lines[i].contains("V-"))
				position=Integer.parseInt(lines[i].split("\t")[0].trim());
		}
		return position;
	}
	public static Double getPatternScore(String sentence, String verb, Double verbscore, String candidate, Integer verbpos)
	{
		Double score=verbscore;		
		int canpos=sentence.indexOf(candidate);
		if (verbpos>canpos) score=0.0;
		return score;
	}
/*
 * sentence id like Amazon.com-21294-64
 */
	public static String readSentence(String sentenceid)
	{
		String filepath="C:\\Documents and Settings\\I820753\\Desktop\\dataset\\testing company\\";
		String thissent="";
		
		String file=sentenceid.split("-")[0].replace("_", " ").replace("wiki", "").trim()+"_wiki.segsent";
	//	System.out.println(sentenceid+"file: "+file);
		String content=Utils.readFile(file);
	//	System.out.println(content);
		if (!sentenceid.contains("-")) return null;
		String sentenceno=sentenceid.split("-")[1];
		String [] lines=content.split("\n");
		boolean find=false;
		for (int i=0;i<lines.length;i++)
		{
			String sentno=lines[i].split("\t")[0];
			if (sentno.equals(sentenceno))
			{
	//			System.out.println("==>"+lines[i]);
				thissent=lines[i];
				find=true;
			}
		}
		if (!find)
		{
			System.out.println(sentenceid);
			System.out.println("-->fail"+sentenceno);
		}
		return thissent;
	}
	
	public static String extractMainVerb(String sentence, String nounphrase)
	{
		String pos=seperateWikipediaArticleSentence.toString(seperateWikipediaArticleSentence.pos(sentence, "text"));
		Integer nounphrasepos=sentence.indexOf(nounphrase);
		String verb="";
		Integer verbpos=0;
		String [] lines=pos.split("\n");
		String stemed="";
		boolean containVerb=false;
		sentence=sentence.split("\t")[1];
	//	System.out.println(sentence);
//		System.out.println(nounphrase+ " "+nounphrasepos+" "+sentence);
		for (int i=0;i<lines.length;i++)
		{	
			if (lines[i].contains("V-"))//||resultlist.get(n).contains("V-Pres-Sg-be"))
			{
	//			System.out.println(lines[i]);
				verb=lines[i].split("\t")[1].trim();
				int cur=Integer.parseInt(lines[i].split("\t")[0].trim());
				
	//			System.out.println(stemed);
				containVerb=true;
				if (cur>nounphrasepos) break;
				verbpos=cur;
				stemed=stem(verb,"text");
			}
		}
		
		return stemed+"\t"+verbpos;
	}
	
	public static String stem (String text, String htformat)
	{
		String linguistxpath="c:\\Program Files\\INXIGHT\\LinguistxPlatform3.7\\lx-3\\";

		Utils.writeFile(linguistxpath+"windows-2003-i686-msvc-7.1-32\\test.txt ", text);
		String s="";
		String stemed=text;
		String cmd="\""+linguistxpath+"windows-2003-i686-msvc-7.1-32\\test_platform.exe\" -k 735442535d524e "+
		" -stem " +
		"-d " + "\""+linguistxpath + "lang\"" + 
		" -"+htformat+" " +"\"" +linguistxpath + "windows-2003-i686-msvc-7.1-32\\test.txt\" ";
		try {
//			System.out.println(cmd);
		     Process p = Runtime.getRuntime().exec(cmd);
		    
		    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
		    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
		    while ((s = stdInput.readLine()) != null)   
		    {
		    	if (s.contains(text)&&s.contains("\t"))
		    	{
//		    		System.out.println(s);
		    		stemed=s.split("\t")[1].trim();
		    		if (stemed.contains("|"))
		    			stemed=s.split("\t")[1].trim().split("\\|")[0].trim();
		    	}
		    }
	//	    while ((s = stdError.readLine()) != null)   
	//	    {
	//	    	System.out.println(s);		    
	//	    }
		}
		catch (IOException e) {
			    e.printStackTrace();    
		}
		return stemed;
	}
	
	public static void main(String[] args) {
		
//		writeToEntities();
		
		//generate PatternwithDistance DCG ranking
		/*
		 * verbProbobility.getFreqWeight()=3;
		 * .getCompLocDistWeight()=5;
		 * .getVerbsProductDistantWeight()=13;
		 * .getFreqDistWeight()=7;
		 * .getVerbsDistantWeighFreq5()
		 * .getPMI=15
		 */
		HashMap <String, Double> verbs=verbProbobility.getPMI();
		String filepath="C:\\Documents and Settings\\I820753\\Desktop\\dataset\\location_testing\\";
		String scorefile=".score15";
		File filepaths=new File (filepath);
		File[] files=filepaths.listFiles();
		int filecount=0;
		for (int i=0;i<files.length;i++)
		{
//			if (!files[i].toString().contains("Ask.com_wiki.candidate")) continue;
			File curfile=new File (files[i].toString().replace("_wiki.candidate", scorefile));
			System.out.println(files[i].toString());
			if (curfile.exists()) continue;
			String contents=Utils.readFile(files[i].toString());
			String [] lines=contents.split("\n");
			String companyname=files[i].toString().replace(filepath, "").replace("_wiki.candidate", "");
			filecount=filecount+1;
			HashMap <String, Double> candidates=new HashMap<String, Double> ();
			//read every line (candidate entity) in the article
			for (int m=0;m<lines.length;m++)
			{
				if (lines[m].length()<2) continue;
				String nounphrase=lines[m].split("\t")[0];
	//			if (!nounphrase.equals("BookSurge")) continue;
				String appears=lines[m].split("\t")[1];
				Double score=0.0000000001;

				//appears at more than one place
				if (appears.contains(" "))
				{
					String [] apps=appears.split(" ");
					for (int n=0;n<apps.length;n++)
					{
						System.out.println(nounphrase+" "+apps[n]);
						String sentence=readSentence(apps[n]);
						System.out.println(sentence);
						String mainverbpos=extractMainVerb(sentence, nounphrase);
						String mainverb=mainverbpos.split("\t")[0];
						System.out.println(nounphrase+" "+sentence);
						System.out.println(mainverbpos);
						Double sc=0.0;
						if (verbs.containsKey(mainverb))
							sc=verbs.get(mainverb);
						score=score+sc;
						System.out.println(nounphrase+" "+sc+" "+mainverb+" "+mainverbpos+" "+sentence);
					}
				}else
				{
			//		System.out.println(nounphrase+" "+appears);
					String sentence=readSentence(appears);
					String pos=seperateWikipediaArticleSentence.toString(seperateWikipediaArticleSentence.pos(sentence, "text"));
					String mainverbpos=extractMainVerb(sentence, nounphrase);
			//		System.out.println(nounphrase+" "+sentence);
			//		System.out.println(mainverbpos);
					String mainverb=mainverbpos.split("\t")[0];
					if (verbs.containsKey(mainverb))
						score=verbs.get(mainverb);
			//		System.out.println(nounphrase+" "+mainverb+" "+mainverbpos+" "+sentence);
				}
	//			System.out.println(companyname+" "+nounphrase+" "+score);
				candidates.put(companyname+"\t"+nounphrase,score);
			}
			
			//sort by value
			ArrayList as = new ArrayList( candidates.entrySet() );
	        
	        Collections.sort( as , new Comparator() {public int compare( Object o1 , Object o2 )
	            {
	                Map.Entry e1 = (Map.Entry)o1 ;
	                Map.Entry e2 = (Map.Entry)o2 ;
	                Double first = (Double)e1.getValue();
	                Double second = (Double)e2.getValue();
	                return second.compareTo( first );
	            }
	        });
	        
	        Iterator it = as.iterator();
	        while ( it.hasNext() )
	        {
	            String pair=((Map.Entry)it.next()).toString() ;
	            String terms=pair.split("=")[0];
	            String score=pair.split("=")[1];
	            System.out.println(terms+"\t"+score);
	            System.out.println(files[i].toString().replace(".candidate",scorefile ));
	            Utils.writeToFile(files[i].toString().replace(".candidate",scorefile ), terms+"\t"+score, true, true);
	        }
		}
		System.out.println(filecount);
	}
}